import Mock from 'mockjs'

function param2Obj(url) {
  const search = url.split('?')[1]
  if (!search) {
    return {}
  }
  return JSON.parse(
    '{"' +
    decodeURIComponent(search)
      .replace(/"/g, '\\"')
      .replace(/&/g, '","')
      .replace(/=/g, '":"') +
    '"}'
  )
}

let userList = []
const count = 100

for (let i = 0; i < count; i++) {
  userList.push(
    Mock.mock({
      id: Mock.Random.guid(),
      username: Mock.Random.cname(),
      permission: Mock.Random.integer(0, 2)
    })
  )
}

export default {
  getUserList: config => {
    const { username, page = 1, limit = 20 } = param2Obj(config.url)
    const mockList = userList.filter(user => {
      if (username && user.username.indexOf(username) === -1) return false
      return true
    })
    const pageList = mockList.filter((item, index) => index < limit * page && index >= limit * (page - 1))
    return {
      code: 20000,
      count: mockList.length,
      list: pageList
    }
  },
  createUser: config => {
    const { username, permission } = JSON.parse(config.body)
    userList.unshift({
      id: Mock.Random.guid(),
      username: username,
      permission: permission
    })
    return {
      code: 20000,
      data: {
        message: '添加成功'
      }
    }
  },
  deleteUser: config => {
    const { id } = JSON.parse(config.body)
    if (!id) {
      return {
        code: -999,
        message: '参数不正确'
      }
    } else {
      userList = userList.filter(u => u.id !== id)
      return {
        code: 20000,
        message: '删除成功'
      }
    }
  },
  updateUser: config => {
    const { id, username, permission } = JSON.parse(config.body)
    userList.some(u => {
      if (u.id === id) {
        u.username = username
        u.permission = permission
        return true
      }
    })
    return {
      code: 20000,
      data: {
        message: '编辑成功'
      }
    }
  }
}
